package com.ajocer.springbootinit.controller;

import cn.hutool.core.io.FileUtil;
import com.ajocer.springbootinit.common.BaseResponse;
import com.ajocer.springbootinit.common.ErrorCode;
import com.ajocer.springbootinit.common.ResultUtils;
import com.ajocer.springbootinit.constant.FileConstant;
import com.ajocer.springbootinit.exception.BusinessException;
import com.ajocer.springbootinit.manager.CosManager;
import com.ajocer.springbootinit.model.dto.file.UploadFileRequest;
import com.ajocer.springbootinit.model.entity.User;
import com.ajocer.springbootinit.model.enums.FileUploadBizEnum;
import com.ajocer.springbootinit.service.UserService;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件接口
 * */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private UserService userService;

    @Resource
    private CosManager cosManager;

    /**
     * 文件上传
     *
     * @param multipartFile
     * @param uploadFileRequest
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile multipartFile,
            UploadFileRequest uploadFileRequest, HttpServletRequest request) {
        if (multipartFile == null || multipartFile.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "上传文件为空");
        }
        
        if (uploadFileRequest == null || uploadFileRequest.getBiz() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "业务类型为空");
        }
        
        String biz = uploadFileRequest.getBiz();
        log.info("开始处理文件上传请求，业务类型：{}", biz);
        
        // 校验业务类型
        FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(biz);
        if (fileUploadBizEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "业务类型不存在");
        }
        
        // 校验文件
        validFile(multipartFile, fileUploadBizEnum);
        
        // 获取当前登录用户
        User loginUser;
        try {
            loginUser = userService.getLoginUser(request);
            if (loginUser == null || loginUser.getId() == null) {
                throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
            }
        } catch (Exception e) {
            log.error("获取登录用户失败", e);
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "请先登录");
        }
        
        // 文件目录：根据业务、用户来划分
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = FilenameUtils.getExtension(originalFilename);
        String uuid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
        String filename = uuid + "." + suffix;
        String filepath = String.format("%s/%s/%s", fileUploadBizEnum.getValue(), loginUser.getId(), filename);
        
        // 去掉开头的斜杠，避免COS路径问题
        if (filepath.startsWith("/")) {
            filepath = filepath.substring(1);
        }
        
        log.info("准备上传文件：{}", filepath);
        
        File tempFile = null;
        try {
            // 创建临时文件
            tempFile = File.createTempFile("upload_", "." + suffix);
            log.info("创建临时文件：{}", tempFile.getAbsolutePath());
            
            // 将上传的文件内容写入临时文件
            multipartFile.transferTo(tempFile);
            
            // 上传到COS
            String fileUrl = cosManager.putObject(filepath, tempFile);
            log.info("文件上传成功，URL：{}", fileUrl);
            
            return ResultUtils.success(fileUrl);
        } catch (IOException e) {
            log.error("文件上传失败，文件名：{}，错误：{}", originalFilename, e.getMessage(), e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("文件上传失败，文件名：{}，错误：{}", originalFilename, e.getMessage(), e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally {
                // 删除临时文件
            if (tempFile != null && tempFile.exists()) {
                boolean deleted = tempFile.delete();
                if (!deleted) {
                    log.warn("临时文件删除失败：{}", tempFile.getAbsolutePath());
                }
            }
        }
    }

    /**
     * 校验文件
     *
     * @param multipartFile
     * @param fileUploadBizEnum 业务类型
     */
    private void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 原始文件名
        String originalFilename = multipartFile.getOriginalFilename();
        // 文件后缀
        String fileSuffix = FilenameUtils.getExtension(originalFilename);
        
        log.info("校验文件：大小={}字节，文件名={}，后缀={}", fileSize, originalFilename, fileSuffix);
        
        final long ONE_M = 1024 * 1024L;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum) 
            || FileUploadBizEnum.SPOT_AVATAR.equals(fileUploadBizEnum)
            || FileUploadBizEnum.SPOT_ROUTE_AVATAR.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 1M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix.toLowerCase())) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误，仅支持jpeg/jpg/svg/png/webp格式");
            }
        }
    }
}
